package com.bufbomb.datastore.admin;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.*;

import com.bufbomb.datastore.PMF;
import com.bufbomb.datastore.StoreUser;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class AccountServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(AccountServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();			
		if (!userService.isUserLoggedIn()) 
		{
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
			return;
		}
		else if(!userService.isUserAdmin()) 
		{
			resp.setContentType("text/plain");
			resp.getWriter().println("You should log in as administrator.");
			//resp.getWriter().println("<a href='" + userService.createLogoutURL("/index.html") + "'> sign out </a>");
		}else
		{
			resp.setContentType("text/html");
			String action = req.getParameter("action");
			if("add".equals(action))
			{
				String email = req.getParameter("email");
				if(email != null)
				{
					if(this.addAccount(email, 10, 100 * 1000))
					{
						resp.getWriter().println("Successfully.");
					}else
					{
						resp.getWriter().println("Failed.");
					}
				}else
				{
					resp.getWriter().println("Failed.");
				}
			}else if("delete".equals(action))
			{
				String email = req.getParameter("email");
				if(email != null)
				{
					if(this.removeAccount(email))
					{
						resp.getWriter().println("Successfully.");
					}else
					{
						resp.getWriter().println("Failed.");
					}
				}else
				{
					resp.getWriter().println("Failed.");
				}
			}else
			{
				resp.getWriter().println(this.getRecordsHTML());
			}
		}
	}
	
	public String getRecordsHTML()
	{
		StringBuilder sb = new StringBuilder();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			Query query = pm.newQuery(StoreUser.class);
			//String query = "select from " + StoreUser.class.getName();
			List<StoreUser> records = (List<StoreUser>) query.execute();
			if (records.isEmpty()) {
				sb.append("Empty");
			}
			else{
				for(StoreUser su : records)
				{
					sb.append(su.getEmail());
					sb.append("<br />");
				}
			}
		}
		finally
		{
			pm.close();
		}
		return sb.toString();
	}
	
	public boolean addAccount(String email, int maxCount, int maxSize)
	{
		boolean result = true;
		StoreUser us = new StoreUser(email, maxCount, maxSize);
		PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(us);
        } 
        catch(Exception e)
        {
        	result = false;
        }finally 
        {
            pm.close();
        }
		return result;
	}
	
	public boolean removeAccount(String email)
	{
		boolean result = true;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			Query query = pm.newQuery(StoreUser.class);
			query.setFilter("email==targetEmail");
			query.declareParameters("String targetEmail");
			//String query = "select from " + StoreUser.class.getName() + " where email==" + email;
			List<StoreUser> records = (List<StoreUser>) query.execute(email); 
			if (records.isEmpty()) {
				result = false;
			}
			else
			{
				StoreUser su = records.get(0);
				pm.deletePersistent(su);
			}
		}
		finally
		{
			pm.close();
		}
		return result;
	}
}
